package com.jakewharton.rxbinding4.component;

import com.jakewharton.rxbinding4.InitialValueObservable;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.Text;

final class TextTextUpdateEventObservable extends InitialValueObservable<TextTextUpdateEvent> {
    private final Text view;

    TextTextUpdateEventObservable(@NonNull Text view) {
        this.view = view;
    }

    @Override
    protected void subscribeListener(Observer<? super TextTextUpdateEvent> observer) {
        Listener listener = new Listener(view, observer);
        observer.onSubscribe(listener);
        view.addTextObserver(listener);
    }

    @Override
    protected TextTextUpdateEvent getInitialValue() {
        return TextTextUpdateEvent.create(view, view.getText(), 0, 0, 0);
    }

    static final class Listener extends MainThreadDisposable implements Text.TextObserver {
        private final Text view;
        private final Observer<? super TextTextUpdateEvent> observer;

        Listener(Text view, Observer<? super TextTextUpdateEvent> observer) {
            this.view = view;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            view.removeTextObserver(this);
        }

        @Override
        public void onTextUpdated(String text, int start, int before, int count) {
            if (!isDisposed()) {
                observer.onNext(TextTextUpdateEvent.create(view, text, start, before, count));
            }
        }
    }
}
